package com.baitengsoft.patentapimonitor.api.controller;

import cn.hutool.core.io.file.FileReader;
import com.baitengsoft.patentapimonitor.api.entity.FileUploadRecordEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebUserinfoEntity;
import com.baitengsoft.patentapimonitor.api.service.FileUploadRecordService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SearchParam;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 数据管理controller
 * @author Chen 2017/12/20
 */
@RestController
@RequestMapping("/api/v1/web")
@Api(value = "前台-数据管理",description = "数据管理")
public class WebDataManagerController extends AbstractController {
    @Autowired
    private FileUploadRecordService fileUploadRecordService;

    /**
     * 申请数据导入
     */
    @ApiOperation(value = "申请数据导入")
    @ResponseBody
    @PostMapping(value = "/sys/datamanager/import",consumes = "multipart/*",headers = "content-type=multipart/form-data")
    public Res importXlsFile(@ApiParam(value = "上传文件",required = true)
                                   @RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
        if(file == null || !file.getOriginalFilename().contains(".xls"))
            return Res.error("文件格式有误,请上传.xls文件");
        String originalFilename = file.getOriginalFilename();
        String prefix=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        if (StringUtils.isBlank(prefix)){
            return Res.error("文件格式有误,请上传.xls文件");
        }
        if (!prefix.equals("xls")){
            return Res.error("文件格式有误,请上传.xls文件");
        }
        if (getUserInfo() == null || getUserInfo().getPlatformid() ==null)
            return Res.error("平台信息获取失败");
        return fileUploadRecordService.importPatInfoByPlatforomId(getUserInfo().getPlatformid(), file);
    }

    /**
     * 下载模板
     */
    @ApiOperation(value = "模板下载")
    @GetMapping(value = "/sys/datamanager/download")
    public Res exportXlsFile(HttpServletResponse response) throws IOException{
        String path = "/excel-templates/uploadtemplate.xls";
        Resource classPathResource = new ClassPathResource(path);
        ServletOutputStream os = response.getOutputStream();
        String fileName = "专利申请数据标准格式.xls";
        fileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        InputStream inputStream=new BufferedInputStream(classPathResource.getInputStream());
        byte[] b=new byte[1024];
        int length;
        while ((length= inputStream.read(b))!=-1){
            os.write(b,0,length);
        }
        os.flush();
        os.close();
        inputStream.close();
        return Res.ok();
    }


    @ApiOperation(value = "获取上传记录")
    @GetMapping(value = "/sys/datamanager/list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "pageNumber", value = "页号", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "pageSize", value = "每页多少条", required = true)

    })
    public Res list(@ApiIgnore SearchParam searchParam){
        WebUserinfoEntity userInfo = getUserInfo();
        if (userInfo ==null || userInfo.getPlatformid()==null){
            return Res.error("登录信息失效");
        }
        PageResult<FileUploadRecordEntity> result = fileUploadRecordService.queryList(userInfo.getPlatformid(),searchParam);
        return Res.ok().put("list",result);
    }

    @ApiOperation(value = "删除")
    @PostMapping(value = "/sys/datamanager/delete/{id}")
    public Res delete(@PathVariable Integer id){
        WebUserinfoEntity userInfo = getUserInfo();
        if (userInfo ==null || userInfo.getPlatformid()==null){
            return Res.error("登录信息失效");
        }
        return fileUploadRecordService.delete(userInfo.getPlatformid(),id);
    }

    @ApiOperation(value = "下载用户上传的文件")
    @GetMapping(value = "/sys/datamanager/userfile")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "fileUrl", value = "fileUrl", required = true),
    })
    public Res userfile(@ApiIgnore String fileUrl,HttpServletResponse response){
        WebUserinfoEntity userInfo = getUserInfo();
        if (userInfo ==null || userInfo.getPlatformid()==null){
            return Res.error("登录信息失效");
        }
        if (StringUtils.isBlank(fileUrl)) return Res.error("参数有误");
        return fileUploadRecordService.download(userInfo.getPlatformid(),fileUrl,response);
    }

}
